/ leetcodesolve / 443. String Compression.py
swadhinbiswas solve more problems · 5/29/2025
2b21c8b
19 lines · 456 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution:
    def compress(self, c: list[str]) -> int:
        n = len(c)
        if n == 0: return 0
        w = 0
        r = 0
        while r < n:
            x = c[r]
            cnt = 0
            while r < n and c[r] == x:
                r += 1
                cnt += 1
            c[w] = x
            w += 1
            if cnt > 1:
                for d in str(cnt):
                    c[w] = d
                    w += 1
        return w